using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using MapLibrary;
using GUILibrary;
using Input;
using Animation;
using UtilityLibrary;
using MapLibrary.GUI;
using MapLibrary.Utility;

namespace Game
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        GameWorld GameWorld;
        GameInput GameInput;
        GUIScreenManager GUIManager;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            graphics.PreferredBackBufferHeight = 800;
            graphics.PreferredBackBufferWidth = 1280;
            graphics.ApplyChanges();
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            this.IsMouseVisible = true;

            GameInput = new GameInput();
            GameWorld = new GameWorld(GraphicsDevice, Content);
            GameWorld.OnLevelLoad += LoadWorldDepenedentGUI;

            GameInput.AddKeyboardListener(GameWorld);
            GameInput.AddMouseListener(GameWorld);


            InitFactories();

            GameStateManager.Instance.OnStateChange += SwitchGUI;

            base.Initialize();
        }

        private void SwitchGUI()
        {
            if (GameStateManager.Instance.IsCurrentState(
                GameStateManager.GameState.GameOver))
                GUIManager.SwitchScreen("GameOver");
        }

        /// <summary>
        /// Loads custom GUI elements that depend on the world being loaded.
        /// For example this includes the SkillUpgradeGUI.
        /// </summary>
        private void LoadWorldDepenedentGUI()
        {
            LoadSkillGUI();
            LoadInGameGUI();
        }


        /// <summary>
        /// Connects the player to components of the InGameGUI that listen to it.
        /// </summary>
        private void LoadInGameGUI()
        {
            for (int i = 1; i <= 3; i++)
            {
                VerticalBar bar = GUIManager.GUIScreens["InGameGUI"].GetComponentByName("CoolDown" + i)
                as VerticalBar;
                bar.ToTrack = GameWorld.CurrentLevel.Player.Skill[i];
            }

            HorizontalBar horBar = GUIManager.GUIScreens["InGameGUI"].GetComponentByName("PlayerLife")
                as HorizontalBar;
            horBar.ToTrack = GameWorld.CurrentLevel.Player;

            RepeatDrawComponent repComp = GUIManager.GUIScreens["InGameGUI"].GetComponentByName("PlayerLives")
                as RepeatDrawComponent;
            repComp.ToTrack = GameWorld.CurrentLevel.Player;
        }

        /// <summary>
        /// Connects the player to components of the Skill GUI that listen to it.
        /// </summary>
        private void LoadSkillGUI()
        {
            for (int i = 0; i < 3; i++)
            {
                VerticalBar bar =
                    GUIManager.GUIScreens["SkillGUI"].GetComponentByName("PlayerProtein" + i) as VerticalBar;

                if (bar != null)
                {
                    bar.ToTrack = GameWorld.CurrentLevel.Player;
                }

                TextFormatComponent textComp =
                        GUIManager.GUIScreens["SkillGUI"].GetComponentByName("PlayerProteinText" + i) as TextFormatComponent;

                if (textComp != null)
                {
                    textComp.ToTrack = GameWorld.CurrentLevel.Player;
                }
            }

            for (int i = 0; i < 4; i++)
            {

                TextFormatComponent prefixDisp =
                    GUIManager.GUIScreens["SkillGUI"].GetComponentByName("SkillLevel" + i) as TextFormatComponent;

                if (prefixDisp != null)
                {
                    prefixDisp.ToTrack = GameWorld.CurrentLevel.Player;
                }

                for (int j = 0; j < 3; j++)
                {
                    HorizontalFillBar bar =
                        GUIManager.GUIScreens["SkillGUI"].GetComponentByName("ProteinBar" + (i*3 + j)) as HorizontalFillBar;
                    if (bar != null)
                    {
                        bar.ToTrack = GameWorld.CurrentLevel.Player;
                    }

                    TextFormatComponent formatComp =
                    GUIManager.GUIScreens["SkillGUI"].GetComponentByName("ProteinBarText" + (i * 3 + j)) as TextFormatComponent;

                    if (formatComp != null)
                    {
                        formatComp.ToTrack = GameWorld.CurrentLevel.Player;
                    }
                }
            }
        }

        private void InitFactories()
        {
            SpriteFactory.Init(Content);
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            UtilityLibrary.PrimitiveBrush.LoadContent(Content);

            GUIManager = this.Content.Load<GUIScreenManager>(@"GUI/screen_manager");
            GUIManager.Initialize(GraphicsDevice);
            GameInput.AddMouseListener(GUIManager);
            GameInput.AddKeyboardListener(GUIManager);

            GameWorld.LoadWorld();
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            if (GameStateManager.Instance.IsCurrentState(GameStateManager.GameState.Quitting))
                this.Exit();

            GameInput.Update();
            GUIManager.Update();
            GameWorld.Update(gameTime);

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here, lul
            GameWorld.Draw();
            GUIManager.Draw();
            base.Draw(gameTime);
        }
    }
}
